/*
  Copyright 2011 Jonathan Albarrán León

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package com.jaal.movilconsultanet;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.DateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xmlpull.v1.XmlSerializer;

import android.content.Context;
import android.util.Log;
import android.util.Xml;

public class XMLContent {	
	
	private static Context context;
	private static final String LAST_MODIFIED = "last_modified";

	public static Context getContext() {
		return context;
	}

	public static void setContext(Context context) {
		XMLContent.context = context;
	}

	private static String generateXml(String root, Map<String, String> datos) {
		XmlSerializer serializer = Xml.newSerializer();
		StringWriter writer = new StringWriter();

		try {
			serializer.setOutput(writer);
			serializer.startDocument("UTF-8", true);
			serializer.startTag("", root);

			Set<Entry<String, String>> datosSet = datos.entrySet();

			for (Entry<String, String> entry : datosSet) {
				serializer.startTag("", entry.getKey());
				serializer.text(entry.getValue());
				serializer.endTag("", entry.getKey());
				Log.d("MCN", "<XML generateXML> "+entry.getKey()+"    "+entry.getValue());
			}
			
			//coloco la ultima modificacion
			serializer.startTag("", LAST_MODIFIED);
			
			DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, Locale.getDefault());
			
			serializer.text(df.format(new Date()));
			serializer.endTag("", LAST_MODIFIED);
			
			serializer.endTag("", root);
			serializer.endDocument();
			return writer.toString();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	private static String generateXmlTree(String root, Map<String, Map<String, String>> datos) {
		XmlSerializer serializer = Xml.newSerializer();
		StringWriter writer = new StringWriter();

		try {
			serializer.setOutput(writer);
			serializer.startDocument("UTF-8", true);
			serializer.startTag("", root);

			Set<Entry<String, Map<String, String>>> datosSet = datos.entrySet();

			for (Entry<String, Map<String, String>> entry : datosSet) {
				serializer.startTag("", entry.getKey());
				
				Set<Entry<String, String>> innerDatosSet = entry.getValue().entrySet();
				
				for (Entry<String, String> innerEntry : innerDatosSet) {
					
					serializer.startTag("", innerEntry.getKey());
					serializer.text(innerEntry.getValue());
					serializer.endTag("", innerEntry.getKey());
					Log.d("MCN", "<XML generateXML> "+innerEntry.getKey()+"    "+innerEntry.getValue());
				}
				serializer.endTag("", entry.getKey());
				Log.d("MCN", "<XML generateXML> "+entry.getKey()+"    "+entry.getValue());
			}
			
			//coloco la ultima modificacion
			serializer.startTag("", LAST_MODIFIED);
			
			DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT, Locale.getDefault());
			
			serializer.text(df.format(new Date()));
			serializer.endTag("", LAST_MODIFIED);
			
			serializer.endTag("", root);
			serializer.endDocument();
			return writer.toString();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

public synchronized static Map<String, String> getXML(String contenido){
		
		Map<String, String> mMap = new HashMap<String, String>();
		FileInputStream fis = null;
		try {
			fis = context.openFileInput(contenido+".xml");
			
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document doc = builder.parse(fis);
			doc.getDocumentElement().normalize();
			
			NodeList rootNodeList = doc.getElementsByTagName(contenido);
			
			NodeList nodeList = rootNodeList.item(0).getChildNodes();
			
			for (int i = 0; i < nodeList.getLength(); i++) {
				Node nodo = nodeList.item(i);
				mMap.put(nodo.getNodeName(), nodo.getFirstChild().getNodeValue());
				Log.d("MCN", "<XML getXML> "+nodo.getNodeName()+"    "+nodo.getFirstChild().getNodeValue());
			}
			fis.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		} catch (FactoryConfigurationError e) {
			e.printStackTrace();
			return null;
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
			return null;
		} catch (SAXException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} finally {
			try {
				if (fis != null) {
					fis.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return mMap;
	}

public synchronized static Map<String, Map<String, String>> getXMLTree(String contenido){
	
	Map<String, Map<String, String>> mMap = new HashMap<String, Map<String, String>>();
	FileInputStream fis = null;
	try {
		fis = context.openFileInput(contenido+".xml");
		
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document doc = builder.parse(fis);
		doc.getDocumentElement().normalize();
		
		NodeList rootNodeList = doc.getElementsByTagName(contenido);
		
		NodeList nodeList = rootNodeList.item(0).getChildNodes();
		
		
		for (int i = 0; i < nodeList.getLength(); i++) {
			
			NodeList innerNodeList = nodeList.item(i).getChildNodes();

			Map<String, String> innermMap = new HashMap<String, String>();

			Node nodo = nodeList.item(i);
			
			//si el nodo es la fecha de actualizacion, entonces no entro a iterar, aqui solo esta el texto de la fecha
			if (nodo.getNodeName().equalsIgnoreCase(LAST_MODIFIED)) {
				
				innermMap.put(nodo.getNodeName(), nodo.getFirstChild().getNodeValue());
				
			} else {
				for (int j = 0; j < innerNodeList.getLength(); j++) {
					
					Node innerNodo = innerNodeList.item(j);
					innermMap.put(innerNodo.getNodeName(), innerNodo.getFirstChild().getNodeValue());
					Log.d("MCN", "<XML getXML> "+innerNodo.getNodeName()+"    "+innerNodo.getFirstChild().getNodeValue());
				}
			}
			
			mMap.put(nodo.getNodeName(), innermMap);
		}
		fis.close();
	} catch (FileNotFoundException e) {
		e.printStackTrace();
		return null;
	} catch (FactoryConfigurationError e) {
		e.printStackTrace();
		return null;
	} catch (ParserConfigurationException e) {
		e.printStackTrace();
		return null;
	} catch (SAXException e) {
		e.printStackTrace();
		return null;
	} catch (IOException e) {
		e.printStackTrace();
		return null;
	} finally {
		try {
			if (fis != null) {
				fis.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	return mMap;
}
	
	
	public synchronized static void saveXML(String contenido, Map<String, String> datos) {
		FileOutputStream fos = null;
		PrintWriter pw = null;
		try {
			Log.d("MCN", "<XML saveXML> "+contenido+" "+datos);
			String xml = generateXml(contenido, datos);

			fos = context.openFileOutput(contenido+".xml", 0);

			pw = new PrintWriter(fos);
			pw.write(xml);
			pw.flush();
			pw.close();
			fos.close();

			Log.d("MCN", "<XML saveXML> saved");

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (pw != null) {
					pw.close();
				}
				if (fos != null) {
					fos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public synchronized static void saveXMLTree(String contenido, Map<String, Map<String, String>> datos) {
		FileOutputStream fos = null;
		PrintWriter pw = null;
		try {
			Log.d("MCN", "<XML saveXML> "+contenido+" "+datos);
			String xml = generateXmlTree(contenido, datos);

			fos = context.openFileOutput(contenido+".xml", 0);

			pw = new PrintWriter(fos);
			pw.write(xml);
			pw.flush();
			pw.close();
			fos.close();

			Log.d("MCN", "<XML saveXML> saved");

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (pw != null) {
					pw.close();
				}
				if (fos != null) {
					fos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
